//
//  ZGLCityListVC.m
//  Faker
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "ZGLCityListVC.h"
#import "ZGLHTTPTOOL.h"
#import "ZGLPlayLocationVC.h"
#import "ZGLPlayResultTVC.h"
#import "NSString+Characters.h"


#pragma mark 1 - 签协议 声明属性
@interface ZGLCityListVC ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchResultsUpdating, ZGLPlayResultTVCDelegate>


//ZGLPlayResultTVC属性
@property (nonatomic, strong) ZGLPlayResultTVC *resultTVC;
//铺城市界面所需的数组和字典属性
@property (nonatomic, strong) NSMutableDictionary *cityDic;
@property (nonatomic, strong) NSMutableArray *keyArr;
@property (nonatomic, strong) NSMutableArray *allCities;
@property (nonatomic, strong) NSArray *hotCity;
@property (nonatomic, retain) NSArray *tempArr;

@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation ZGLCityListVC

-(void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;
    self.tableView.backgroundColor = foreColor;
    [self.tableView reloadData];
}
-(void)viewWillDisappear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark 2 - 内存管理
-(void)dealloc {
    self.searchController.searchBar.delegate = nil;
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
    self.resultTVC.delegate = nil;
    self.searchController.searchResultsUpdater = nil;
}
#pragma mark 3 - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zaihufanhui"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItem)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    [self handleData];
    [self creatTableView];
    [self creatSearchBar];
    // Do any additional setup after loading the view.
}
/* leftBarButtonItem点击事件 */
-(void)leftBarButtonItem {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 4 - 数据处理
-(void)handleData {
    self.keyArr = [NSMutableArray arrayWithCapacity:0];
    self.allCities = [NSMutableArray arrayWithCapacity:0];
    self.hotCity = @[@"北京", @"上海", @"广州", @"深圳", @"成都", @"重庆", @"杭州", @"武汉", @"南京", @"苏州", @"天津", @"郑州", @"济南", @"昆明", @"石家庄", @"长沙", @"沈阳", @"西安", @"大连", @"青岛"];
    self.cityDic = @{
                     @"A" : @[@"安庆", @"安顺", @"安阳", @"阿拉善盟", @"鞍山", @"阿坝", @"阿里", @"阿克苏", @"阿勒泰", @"安康", @"阿拉尔"],
                     @"B" : @[@"北京", @"蚌埠", @"毫州", @"白银", @"北海", @"百色", @"毕节", @"保定", @"包头", @"巴彦淖尔", @"白山", @"本溪", @"滨州", @"巴中", @"博尔塔拉", @"巴音郭楞", @"保山", @"宝鸡", @"白城", @"保亭"],
                     @"C" : @[@"成都", @"常州", @"重庆", @"滁州", @"巢湖", @"池州", @"潮州", @"崇左", @"承德", @"沧州", @"常德", @"郴州", @"赤峰", @"朝阳", @"昌都", @"昌吉", @"楚雄", @"大理", @"长春", @"长沙", @"长治"],
                     @"D" : @[@"定西", @"东莞", @"大庆", @"大兴安岭", @"大连", @"丹东", @"大同", @"东营", @"德州", @"德阳", @"达州", @"德宏", @"迪庆", @"大理", @"儋州"],
                     @"E" : @[@"鄂州", @"恩施", @"鄂尔多斯"],
                     @"F" : @[@"福州", @"佛山", @"阜阳", @"防城港", @"抚州", @"抚顺", @"阜新"],
                     @"G" : @[@"广州", @"贵阳", @"桂林", @"甘南", @"贵港", @"赣州", @"固原", @"果洛", @"广元", @"广安", @"甘孜"],
                     @"H" : @[@"杭州", @"合肥", @"海口", @"淮南", @"淮北", @"黄山", @"惠州", @"河源", @"贺州", @"河池", @"邯郸", @"衡水", @"哈尔滨", @"鹤岗", @"黑河", @"鹤壁", @"黄石", @"黄冈", @"衡阳", @"怀化", @"呼和浩特", @"呼伦贝尔", @"淮安", @"葫芦岛", @"海东", @"海北", @"黄南", @"海西", @"菏泽", @"哈密", @"和田", @"红河", @"湖州", @"汉中"],
                     @"J" : @[@"济南", @"嘉兴", @"嘉峪关", @"金昌", @"酒泉", @"江门", @"揭阳", @"鸡西", @"佳木斯", @"焦作", @"济源", @"荆门", @"荆州", @"景德镇", @"九江", @"吉安", @"吉林市", @"锦州", @"晋城", @"晋中", @"济宁", @"金华"],
                     @"K" : @[@"昆明", @"开封", @"克拉玛依", @"克孜勒苏", @"喀什"],
                     @"L" : @[@"洛阳", @"柳州", @"连云港", @"六安", @"龙岩", @"兰州", @"陇南", @"临夏", @"来宾", @"六盘水", @"廊坊", @"漯河", @"娄底", @"辽源", @"辽阳", @"临汾", @"吕梁", @"莱芜", @"临沂", @"聊城", @"泸州", @"乐山", @"凉山", @"拉萨", @"林芝", @"丽江", @"临沧", @"丽水"],
                     @"M" : @[@"马鞍山", @"茂名", @"梅州", @"牡丹江", @"绵阳", @"眉山"],
                     @"N" : @[@"南京", @"宁波", @"南宁", @"南通", @"南平", @"宁德", @"南阳", @"南昌", @"内江", @"南充", @"那曲", @"怒江"],
                     @"P" : @[@"莆田", @"平凉", @"平顶山", @"濮阳", @"萍乡", @"盘锦", @"攀枝花"],
                     @"Q" : @[@"青岛", @"泉州", @"庆阳", @"清远", @"钦州", @"黔西南", @"黔东南", @"黔南", @"秦皇岛" ,@"齐齐哈尔", @"七台河", @"潜江", @"曲靖", @"衢州"],
                     @"R" : @[@"日照", @"日喀则"],
                     @"S" : @[@"上海", @"深圳", @"苏州", @"厦门", @"三亚", @"宿州", @"三明", @"韶关", @"汕头", @"汕尾", @"三沙", @"石家庄", @"双鸭山", @"绥化", @"三门峡", @"商丘", @"十堰", @"随州", @"神农架", @"邵阳", @"宿迁", @"上饶", @"四平", @"松原", @"沈阳", @"石嘴山", @"朔州", @"遂宁", @"山南", @"石河子", @"思茅", @"绍兴", @"商洛"],
                     @"T" : @[@"天津", @"铜陵", @"天水", @"铜仁", @"唐山", @"天门", @"通辽", @"泰州", @"通化", @"铁岭", @"太原", @"泰安", @"吐鲁番", @"塔城", @"台州", @"铜川"],
                     @"W" : @[@"芜湖", @"武威", @"梧州", @"乌海", @"乌兰察布盟", @"无锡", @"吴忠", @"潍坊", @"威海", @"乌鲁木齐", @"文山", @"温州", @"渭南"],
                     @"X" : @[@"西安", @"徐州", @"宣城", @"邢台", @"新乡", @"许昌", @"信阳", @"襄阳", @"孝感", @"咸宁", @"仙桃", @"湘潭", @"西乡土家族苗族自治州", @"兴安盟", @"锡林郭勒", @"新余", @"西宁", @"忻州", @"西双版纳", @"咸阳"],
                     @"Y" : @[@"阳江", @"云浮", @"玉林", @"伊春", @"宜昌", @"岳阳", @"益阳", @"永州", @"盐城", @"扬州", @"鹰潭", @"宜春", @"延边", @"营口", @"银川", @"玉树", @"阳泉", @"运城", @"烟台", @"宜宾", @"雅安", @"伊犁", @"玉溪", @"延安", @"榆林"],
                     @"Z" : @[@"珠海", @"中山", @"漳州", @"张掖", @"湛江", @"肇庆", @"遵义", @"张家口", @"郑州", @"周口", @"驻马店", @"株洲", @"张家界", @"镇江", @"中卫", @"淄博", @"枣庄", @"自贡", @"资阳", @"昭通", @"舟山"]}.mutableCopy;
    self.keyArr = [[self.cityDic allKeys] sortedArrayUsingSelector:@selector(compare:)].mutableCopy;
    [self.keyArr insertObject:@"#" atIndex:0];
    [self.cityDic setObject:self.hotCity forKey:@"#"];
    for (NSString *key in self.cityDic) {
        NSArray *arr = self.cityDic[key];
        for (NSString *str in arr) {
            [self.allCities addObject:str];
        }
    }
    
}
#pragma mark 5 - 创建searchController
-(void)creatSearchBar {
    self.resultTVC = [[ZGLPlayResultTVC alloc] init];
    self.resultTVC.delegate = self;
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultTVC];
    self.resultTVC.cityName = self.currentCity;
    self.searchController.searchBar.placeholder = @"我在...";
    self.searchController.searchBar.delegate = self;
    self.searchController.searchResultsUpdater = self;
    self.searchController.searchBar.backgroundColor = [UIColor redColor];
    self.definesPresentationContext = YES;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, Width, 50 * ScaleX)];
    [self.view addSubview:view];
    self.searchController.searchBar.frame = CGRectMake(0, 0, Width, 50 * ScaleX);
    [view addSubview:self.searchController.searchBar];
}
#pragma mark 6 - TableView部分
/* 创建tableview */
-(void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50 * ScaleX, Width, Height) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}
/* 行数 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *key = [self.keyArr objectAtIndex:section];
    NSArray *arr = [self.cityDic objectForKey:key];
    return arr.count;
}
/* 分区数 */
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.keyArr.count;
}
/* cell赋值 */
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *str = @"ZGLCityListVC_Cell";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
    }
    
    NSString *key = [self.keyArr objectAtIndex:indexPath.section];
    NSArray *arr = [self.cityDic objectForKey:key];
    if ([arr[indexPath.row] isEqualToString:self.currentCity]) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(330 * ScaleX, 12 * ScaleX, 20 * ScaleX, 20 *ScaleX)];
        imageView.image = [UIImage imageNamed:@"sdingyue"];
        [cell addSubview:imageView];
    }
        cell.textLabel.text = arr[indexPath.row];
        cell.backgroundColor = foreColor;
        cell.textLabel.textColor = artiColor;
        return cell;
}
/* Header设置 显示标题 */
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, 20 * ScaleX)];
    view.backgroundColor = [UIColor colorWithWhite:0.974 alpha:1.000];
    NSArray *arr = [self.cityDic objectForKey:self.keyArr[section]];
    if (arr.count == 0) {
        
    }else {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10 * ScaleX, 0, 100 * ScaleX, 20 * ScaleX)];
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor colorWithWhite:0.478 alpha:1.000];
        [view addSubview:label];
        if (0 == section) {
            label.text = @"热门城市";
        }else {
        label.text = self.keyArr[section];
        label.textColor = artiColor;
        }
    }
    view.backgroundColor = foreColor;
    return view;
}
/* Header高度设置 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20 * ScaleX;
}
/* 右侧索引 */
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    self.tableView.sectionIndexBackgroundColor = foreColor;
    self.tableView.sectionIndexColor = artiColor;
    return self.keyArr;
}
#pragma mark 7 - cell选中点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *str = [self.cityDic objectForKey:[self.keyArr objectAtIndex:indexPath.section]][indexPath.row];
    NSArray *arr = [self.navigationController viewControllers];
    ZGLPlayLocationVC *loactionVC = arr[1];
    [self.delegate passCityName:str];
    [self.navigationController popToViewController:loactionVC animated:YES];
}

#pragma mark 8 - UISearchResultUpdating协议方法实现
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchtext = searchController.searchBar.text;
    ZGLPlayResultTVC *tableController = (ZGLPlayResultTVC *)self.searchController.searchResultsController;
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@",searchtext];
    if (searchtext.length == 0) {
        return;
    }
    if (searchtext.length == 1) {
        [tableController.tableView reloadData];
        NSMutableArray *searchResults = (NSMutableArray *)[self.keyArr filteredArrayUsingPredicate:predicate];
        if (searchResults.count == 0) {
            [self.tableView reloadData];
            searchResults = (NSMutableArray *)[self.allCities filteredArrayUsingPredicate:predicate];
            if (searchResults.count == 0) {
                NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"没有您搜索的城市"];
                [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, 8)];
                tableController.dataArray = @[attributeString];
            }
            else {
                
                NSMutableArray *newArr = [NSMutableArray arrayWithCapacity:0];
                for (NSString *strHan in searchResults) {
                    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:strHan];
                    for (NSInteger i = 0; i < strHan.length; i++) {
                        NSString *str  = [strHan substringWithRange:NSMakeRange(i, 1)];
                        if ([str isEqualToString:searchtext]) {
                            [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(i, 1)];
                        }
                    }
                    [newArr addObject:attributeString];
                }
                tableController.dataArray = newArr;
            }
        } else {
            NSArray *tempArr = self.cityDic[searchResults[0]];
            NSMutableArray *resultArr = [NSMutableArray arrayWithCapacity:0];
            for (NSString *str in tempArr) {
                NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:str];
                [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, 1)];
                [resultArr addObject:attributeString];
               
            }
            tableController.dataArray = resultArr;
        }
    } else {
        NSMutableArray *newArr = [NSMutableArray arrayWithCapacity:0];
        self.tempArr = self.cityDic[[[searchtext substringWithRange:NSMakeRange(0, 1)] uppercaseString]];
        for (NSString *str in self.tempArr) {
            NSMutableAttributedString *attributeString = nil;
            NSString *strHan = str;
            NSInteger one_H = 0;
            NSInteger two_H = 0;
            NSInteger three_H = 0;
            NSInteger four_H = 0;
            NSMutableString *strPinyin = [NSMutableString string];
            for (NSInteger i = 0; i < strHan.length; i++) {
                NSString *str  = [strHan substringWithRange:NSMakeRange(i, 1)] ;
                str = [str pinyinOfName];
                if (i == 0) {
                    one_H = str.length;
                }
                if (2 == i) {
                    two_H = str.length;
                }
                if (3 == i) {
                    three_H = str.length;
                }
                if (4 == i) {
                    four_H = str.length;
                }
                [strPinyin appendString:str];
            }
            if ([predicate evaluateWithObject:strPinyin]) {
                if (searchtext.length <= one_H) {
                    attributeString = [[NSMutableAttributedString alloc] initWithString:strHan];
                    [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, 1)];
                }
                if (searchtext.length > one_H && searchtext.length <= one_H +two_H) {
                    attributeString = [[NSMutableAttributedString alloc] initWithString:strHan];
                    [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, 2)];
                }
                if (searchtext.length > one_H +two_H && searchtext.length <= one_H +two_H + three_H) {
                    attributeString = [[NSMutableAttributedString alloc] initWithString:strHan];
                    [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, 3)];
                }
                if (searchtext.length > one_H +two_H + three_H && searchtext.length <= one_H +two_H + three_H + four_H) {
                    attributeString = [[NSMutableAttributedString alloc] initWithString:strHan];
                    [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, 4)];
                }
                if (searchtext.length > one_H +two_H + three_H + four_H) {
                    attributeString = [[NSMutableAttributedString alloc] initWithString:strHan];
                    [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, strHan.length)];
                }
                [newArr addObject:attributeString];
            }
        }
        if (newArr.count == 0) {
            for (NSString *str in self.tempArr) {
                NSString *strHan = str;
                NSMutableString *strPinyin = [NSMutableString string];
                
                for (NSInteger i = 0; i < strHan.length; i++) {
                    NSString *str  = [strHan substringWithRange:NSMakeRange( i, 1)] ;
                    str = [str firstCharacterOfName];
                    [strPinyin appendString:str];
                }
                [strPinyin lowercaseString];
                if ([predicate evaluateWithObject:strPinyin]) {
                    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:strHan];
                    [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, strPinyin.length)];
                    [newArr addObject:attributeString];
                }
                
            }
        }
        if (newArr.count == 0) {
            NSMutableArray *searchResults = (NSMutableArray *)[self.allCities filteredArrayUsingPredicate:predicate];
            if (searchResults.count == 0) {
                NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"没有您搜索的城市"];
                [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, 8)];
                newArr = @[attributeString].mutableCopy;
                } else {
                
                for (NSString *strHan in searchResults) {
                    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:strHan];
                    NSInteger o = 0;
                    NSString *str = [NSString string];
                    for (NSInteger i = 0; i < strHan.length; i++) {
                        str = [strHan substringWithRange:NSMakeRange(i, 1)];
                        
                        NSString *strSe = [searchtext substringWithRange:NSMakeRange(0, 1)];
                        if ([str isEqualToString:strSe]) {
                            o = i;
                        }
                    }
                    [attributeString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(o, searchtext.length)];
                    [newArr addObject:attributeString];
                }
            }
        }
        tableController.dataArray = newArr;
        [tableController.tableView reloadData];
    }
}
#pragma mark 9 - ZGLPlayResultTVC协议方法实现
-(void)passCityName:(NSString *)cityName {
    NSArray *arr = [self.navigationController viewControllers];
    ZGLPlayLocationVC *loactionVC = arr[1];
    [self.delegate passCityName:cityName];
    [self.navigationController popToViewController:loactionVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
